import React, { useState } from 'react';
import { Form, Input, Button, Row, Col, Space, Select,DatePicker,Cascader } from 'antd';
import { DownOutlined, UpOutlined } from '@ant-design/icons';


const { Option } = Select;
// const { RangePicker } = DatePicker;

interface FieldConfig {
  label: string;
  name: string;
  type: 'select' | 'input' | 'datePicker' | 'checkbox' | string;
  options?: { label: string; value: string }[]; // for select
  hidden?: boolean;
  required?: boolean; // ✅ 新增
  fieldProps?: any; // ✅ 加上这一行
}

interface FilterPanelProps {
  fields: FieldConfig[];
  onSearch: (values: Record<string, any>) => void;
  initialValues?: Record<string, any>;
}

const FilterPanel: React.FC<FilterPanelProps> = ({
  fields,
  onSearch,
  initialValues = {},
}) => {
  const [form] = Form.useForm();
  const hiddenFieldsWithValue = fields.slice(5).some(field => initialValues[field.name]);
  const [expanded, setExpanded] = useState(hiddenFieldsWithValue);
  
  const visibleFields = expanded ? fields : fields.slice(0, 5);// 默认显示5项

  const handleFinish = (values: Record<string, any>) => {
    onSearch(values);
  };

  const handleReset = () => {
    form.resetFields();
    onSearch({});
  };

  return (
    <Form
      form={form}
      initialValues={initialValues}
      onFinish={handleFinish}
      layout="inline"
      style={{ marginBottom: 16 }}
    >
      <Row gutter={[16, 8]} style={{ width: '100%' }}>
        {visibleFields.map((field) => (
          <Col key={field.name}>
          <Form.Item
          name={field.name}
          label={
            field.required ? (
              <span>
                <span style={{ color: 'red' }}></span> {field.label}
              </span>
            ) : (
              field.label
            )
          }
          rules={field.required ? [{ required: true, message: `请选择${field.label}` }] : []}
        >
          {field.type === 'input' && <Input placeholder={`请输入${field.label}`} />}
          {field.type === 'select' && (
            <Select
              {...field.fieldProps} // ✅ 关键：透传 fieldProps
              allowClear
              showSearch
              //设置检索时，按照可选项的label属性进行检索，而不是
              filterOption={(input, option) => {
                const label = option?.children || option?.label || '';
                return String(label).toLowerCase().includes(input.toLowerCase());
              }}
              optionFilterProp="label"
              placeholder={`请选择${field.label}`}
              maxTagCount={1} 
              style={{ width: 200 }}
            >
              {field.options?.map((opt) => (
                <Option key={opt.value} value={opt.value}>
                  {opt.label}
                </Option>
              ))}
            </Select>
          )}
          {field.type === 'cascader' && (
            <Cascader
              options={field.options}
              placeholder={`请选择${field.label}`}
              style={{ width: 240 }}
              allowClear
              changeOnSelect // ✅ 如果希望中间层也能被选中
              showSearch={{
                filter: (inputValue, path) =>
                  path.some(
                    (option) =>
                      String(option.label)
                        .toLowerCase()
                        .includes(inputValue.toLowerCase())
                  ),
              }}
            />
        )}
          {field.type === 'datePicker' && (
            <DatePicker
              placeholder={`请选择${field.label}`}
              style={{ width: 160 }}
              format="YYYY-MM-DD"
            />
          )}
          {field.type === 'rangePicker' && (
            <DatePicker.RangePicker
              placeholder={['开始日期', '结束日期']}
              style={{ width: 240 }}
              format="YYYY-MM-DD"
            />
          )}
        </Form.Item>
          </Col>
        ))}
        <Col flex="auto">
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button onClick={handleReset}>重置</Button>
              {fields.length > 5 && (
                <a onClick={() => setExpanded(!expanded)}>
                  {expanded ? (
                    <>
                      收起 <UpOutlined />
                    </>
                  ) : (
                    <>
                      展开 <DownOutlined />
                    </>
                  )}
                </a>
              )}
            </Space>
          </Form.Item>
        </Col>
      </Row>
    </Form>
  );
};

export default FilterPanel;
